﻿using Lamex.Base.Framework.BaseDal;
using Lamex.Common;
using Lamex.SystemManager.Interfaces;
using Lamex.SystemManager.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lamex.SystemManager.DalServer
{
    public class Sys_Menu : BaseDalSQL<Sys_MenuInfo>, ISys_Menu
    {
        /// <summary>
        /// 获取树形结构的菜单列表
        /// </summary>
        bool isDescending;
        public List<MenuNodeInfo> GetTree(string systemType)
        {
            string condition = !string.IsNullOrEmpty(systemType) ? string.Format("AND SystemType='{0}'", systemType) : "";
            List<MenuNodeInfo> arrReturn = new List<MenuNodeInfo>();
            string sql = string.Format("Select * From {0} Where Enabled=1 {1} Order By PID, SortCode ", tableName, condition);

            DataTable dt = base.GetDataTableBySql(sql);
            string sortCode = string.Format("{0} {1}", "SortCode", isDescending ? "DESC" : "ASC");
            DataRow[] dataRows = dt.Select(string.Format(" PID = '{0}' ", -1), sortCode);
            for (int i = 0; i < dataRows.Length; i++)
            {
                string id = dataRows[i]["ID"].ToString();
                MenuNodeInfo menuNodeInfo = GetNode(id, dt);
                arrReturn.Add(menuNodeInfo);
            }

            return arrReturn;
        }

        /// <summary>
        /// 获取所有的菜单列表
        /// </summary>
        public List<Sys_MenuInfo> GetAllMenu(string systemType)
        {
            string condition = !string.IsNullOrEmpty(systemType) ? string.Format("Where SystemType='{0}'", systemType) : "";
            string sql = string.Format("Select * From {0} {1} Order By PID, SortCode ", tableName, condition);
            return ConvertHelper<Sys_MenuInfo>.DataTableToList(GetDataTableBySql(sql));
        }

        private MenuNodeInfo GetNode(string id, DataTable dt)
        {
            Sys_MenuInfo menuInfo = this.GetEntriyList("ID='" + id + "'").FirstOrDefault();
            MenuNodeInfo menuNodeInfo = new MenuNodeInfo(menuInfo);

            string sort = string.Format("{0} {1}", "SortCode", isDescending ? "DESC" : "ASC");
            DataRow[] dChildRows = dt.Select(string.Format(" PID='{0}'", id), sort);

            for (int i = 0; i < dChildRows.Length; i++)
            {
                string childId = dChildRows[i]["ID"].ToString();
                MenuNodeInfo childNodeInfo = GetNode(childId, dt);
                menuNodeInfo.Children.Add(childNodeInfo);
            }
            return menuNodeInfo;
        }

       
    }
}
